package com.richman.view;



import javax.swing.JPanel;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;

import com.richman.controller.AutoBetCentralManager;
import com.richman.controller.NegativeRatioClient;
import com.richman.ps38.entity.BetAdyData;
import com.richman.ps38.entity.BetDvalue;
import com.richman.ps38.entity.Event;
import com.richman.ps38.entity.HGEvent;
import com.richman.ps38.entity.HGISNEvent;
import com.richman.ps38.entity.ISNPS38Event;
import com.richman.ps38.entity.ISNEvent;
import com.richman.ps38.entity.ISNHGSendData;
import com.richman.ps38.entity.SendData;
import com.richman.utils.Common;
import com.richman.utils.SoundThread;

import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class BetCentralPane extends JPanel {

	/**
	 * 
	 */
	private static final long serialVersionUID = -10000L;
	
	private  Vector<String[]> detailsData = new Vector<String[]>();
	
	private Vector<SendData> localgamedetails = new Vector<SendData>();
	
	public Vector<Event> gameDetailsVec = new Vector<Event>(); 
	
	
	
	public Vector<SendData> senddatas = null;
	
	
	public Vector<ISNHGSendData> isnhgsenddatas = null;
	
	public BetWindow betwnd = new BetWindow();
	
	public AutoBetCentralManager autobetCtrMng = new AutoBetCentralManager();
	
	MyTableModel tableMode = new MyTableModel();

	
	JTable table = null;
	
	
	public long lastAddtime = System.currentTimeMillis();

	/**
	 * Create the panel.
	 */
	public BetCentralPane() {
		setLayout(new BorderLayout(0, 0));
		

		
		JPanel funBtnPane = new JPanel();
		
		JButton cleanButton = new JButton("清空数据");
		cleanButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				int n = JOptionPane.showConfirmDialog(null, "确认要清空数据吗?", "清空数据",
						JOptionPane.YES_NO_OPTION);
				if (n == JOptionPane.YES_OPTION) {					
					if(detailsData != null && detailsData.size() != 0) {
						detailsData.clear();
						localgamedetails.clear();
						tableMode.updateTable();
					}
				}
				
			}
		});
		
		cleanButton.setBounds(20, 10, 60, 20);
		
		funBtnPane.add(cleanButton);
		
		add(funBtnPane, BorderLayout.NORTH);
		
	    table = new JTable(tableMode);
	    
	    table.getColumnModel().getColumn(0).setPreferredWidth(120);
	    
	    table.setRowHeight(30);
	    
	    table.setFont(new java.awt.Font("黑体", Font.PLAIN, 15));
		
		
		JScrollPane scrollPane = new JScrollPane(table);
		add(scrollPane, BorderLayout.CENTER);
		

		table.addKeyListener(new KeyAdapter() {

			@Override

			public void keyPressed(KeyEvent e) {

			super.keyPressed(e);

			char c = e.getKeyChar();

			int code = e.getKeyCode();
			
			String text  = "";
			
			
				
				
				if(code == 67) {
					
					text  = "focus on JTable 你按下的键的信息：keyChar = " + c + " KeyCode = " + code;
					
					showBetWnd();
					
					System.out.println(text);
					
				}
				
				
				
			

			

			

			}

			});
        
	
        
		
		//双击table事件
	    table.addMouseListener(new MouseAdapter(){

            public void mouseClicked(MouseEvent e) {
            	
            	
            	
          	  if(e.getClickCount() == 2){
          		  
          		  
          		  boolean bfind = false;
          		  
//          		  if(DaShuiClient.mainWnd.getautobet() == true) {
//          			JOptionPane.showMessageDialog(null,"如需手动投注,请先取消自动投注");
//          			return;
//          		  }
          		  
          		  if(!(NegativeRatioClient.betCtrMng.hgmanager.getStatuscode() == 1)){
          			JOptionPane.showMessageDialog(null,"皇冠账号尚未完成登录，请稍后投注");
          			return;
          		  }
          		  
          		  
          		  if(!(NegativeRatioClient.betCtrMng.ps38manager.getStatuscode() == 2)){
          			JOptionPane.showMessageDialog(null,"ps38账号尚未完成登录，请稍后投注");
          			return;
          		  }
          		  
          		  
              	  int row =((JTable)e.getSource()).rowAtPoint(e.getPoint()); //获得行位置 
              	  
              	if(betwnd.isVisible()) {
    				return;
    			}
              	  
              	  
              	  if(detailsData.elementAt(row)[0].equals("")){
              		  return;
              	  }else{
              		  
//              		  String eventid = detailsData.elementAt(row)[10];
//              		  
//              		  double pankou = Double.parseDouble(detailsData.elementAt(row)[6]);
              		  
              		  
              		  
        				if(betwnd.setgame(detailsData.elementAt(row)[5], detailsData.elementAt(row)[11], localgamedetails.elementAt(row))) {
        					betwnd.setVisible(true);
        				}  
        				
        				
//        				bfind = true;
//        				break;
              		  
              		  
              		  
//              		  for(int i = 0; i < senddatas.size(); i++){
//              			  
//              			  String bettype = detailsData.elementAt(row)[5];
//              			  
//              			  String pankoustr = "";
//              			  String ps38pankoustr = "";
//              			  
//              			  if(bettype.contains("全场让球")) {
//              				  
//              				pankoustr = senddatas.elementAt(i).hgevent.wholerqppankou;
//              				ps38pankoustr = senddatas.elementAt(i).event.wholerqppankou;
//              				  
//              			  }else if(bettype.contains("全场大小")) {
//              				pankoustr = senddatas.elementAt(i).hgevent.wholeDXPPankou;
//              				ps38pankoustr = senddatas.elementAt(i).event.wholeDXPPankou;
//              			  }
//              			  
//              			  
//              			  
//              			if(!Common.isNum(pankoustr)) {
//              				
//              				
//              				//Common.logOut("手动投注  pankoustr:" + pankoustr);
//              				
//              				continue;
//              			  }
//              			  
//              			  
//              			  
//              			  if(eventid.equals(senddatas.elementAt(i).hgevent.eventId) && 
//              					  Math.abs(pankou - Double.parseDouble(pankoustr)) < 0.001 &&
//              					Math.abs(pankou - Double.parseDouble(ps38pankoustr)) < 0.001 ) {
//              				  
//              				betwnd.setgame(detailsData.elementAt(row)[5], detailsData.elementAt(row)[11], senddatas.elementAt(i));  
//              				betwnd.setVisible(true);
//              				
//              				bfind = true;
//              				break;
//              			  }
//              			  
//              			  
//              		  }
              		  
              		  
              		  //betwnd.setgame(gameDetailsVec.elementAt(0));
    				  
              		  
              		  
              	  }
              	  
              	  
//              	  if(bfind == false) {
//              		JOptionPane.showMessageDialog(null,"该记录已失效");
//              	  }
              	  
              	  
              	  
              	  
              	  
          	  }else{
          		  return;
          	  }

            }
      });
		

	}
	
	
	public void updatePS38EventTable(Vector<SendData> gamedetails, Vector<ISNHGSendData> isnhgsenddatasarg){
		
	}
	
	
	
	
//	private void constructBetDvalue() {
//		
//		
//		try {
//			
//			Vector<String> parsealready = new Vector<String>();
//			
//			
//			if(DaShuiClient.betCtrMng.betDvalues != null) {
//				DaShuiClient.betCtrMng.betDvalues.clear();
//			}
//			
//			
//			double maxdvalue = DaShuiClient.mainWnd.getmaxdvalue();
//			
//			for(int i = 0; i < detailsData.size(); i++) {
//				
//				String[] item = detailsData.elementAt(i);
//				
//				
//				if(parsealready.contains(item[10] + item[5].substring(2))) {
//					continue;
//				}
//				
//				
//				parsealready.add(item[10] + item[5].substring(2));
//				
//				
//				boolean bfirstpankou = true;
//				
//				String sfirstpankou = "";
//				
//				for(int j = detailsData.size()-1; j >=0; j--) {
//					
//					
//					String[] item1 = detailsData.elementAt(j);
//					
//					if(item1[10].equals(item[10]) && 
//					   item1[5].substring(2).equals(item[5].substring(2))) {
//						
//						if(bfirstpankou == true) {						
//							
//							bfirstpankou = false;
//							sfirstpankou = item1[6];
//							
//							BetDvalue bdvalue = new BetDvalue();
//							bdvalue.firstpankou = sfirstpankou;
//							bdvalue.league = item1[2];
//							bdvalue.team = item1[4];
//							bdvalue.bettype = item1[5];
//							bdvalue.eventid = item1[10];
//							if(item1[11].equals("1")) {
//								bdvalue.hgps38times++;
//							}else if(item1[11].equals("2")) {
//								bdvalue.ps38hgtimes++;
//							}
//							
//							DaShuiClient.betCtrMng.betDvalues.add(bdvalue);
//							
//
//						}else {
//							
//							for(int k = 0; k < DaShuiClient.betCtrMng.betDvalues.size(); k++) {
//								
//								if(DaShuiClient.betCtrMng.betDvalues.elementAt(k).eventid.equals(item1[10]) &&
//								   DaShuiClient.betCtrMng.betDvalues.elementAt(k).bettype.substring(2).equals(item1[5].substring(2)) &&
//								   Math.abs(Double.parseDouble(DaShuiClient.betCtrMng.betDvalues.elementAt(k).firstpankou) - Double.parseDouble(item1[6])) <= maxdvalue) {
//									
//									if(item1[11].equals("1")) {
//										DaShuiClient.betCtrMng.betDvalues.elementAt(k).hgps38times++;
//									}else if(item1[11].equals("2")) {
//										DaShuiClient.betCtrMng.betDvalues.elementAt(k).ps38hgtimes++;
//									}
//									
//									
//									break;
//									
//								}
//								
//							}
//							
//						}
//						
//					}
//					
//				}
//				
//				
//			}
//			
//			
////			for(int i = 0; i < DaShuiClient.betCtrMng.betDvalues.size(); i++) {
////				System.out.println(DaShuiClient.betCtrMng.betDvalues.elementAt(i).toString());
////			}
//			
//			
//			
//			DaShuiClient.mainWnd.updateBetDvalueTable(DaShuiClient.betCtrMng.betDvalues);
//			
//			
//		}catch(Exception e) {
//			e.printStackTrace();
//		}
//		
//		
//
//	}
//


	public void processAutoBet() {
		
		
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		
		Vector<String> forbidLeagues = NegativeRatioClient.mainWnd.getForbidLeagues();
		Vector<String> negLeagues = NegativeRatioClient.mainWnd.getNegLeagues();
		
		if(NegativeRatioClient.mainWnd.getautobet() == true) {
			
			for(int i = 0; i < detailsData.size(); i++) {
				
				if(forbidLeagues.contains(detailsData.elementAt(i)[2])) {//禁投联赛					
					continue;
				}
				
				//一开始的原版分机 就算是
				if(NegativeRatioClient.bNeg == false) {
					if(negLeagues.contains(detailsData.elementAt(i)[2])) {//也直接跳过反投的联赛
						continue;
					}
				}else {
					if(!negLeagues.contains(detailsData.elementAt(i)[2])) {//反投的版本,只处理反投的联赛,其他联赛跳过
						continue;
					}
				}
				
				if(senddatas != null){
            		  
            		  String eventid = detailsData.elementAt(i)[10];
            		  
            		  double pankou = Double.parseDouble(detailsData.elementAt(i)[6]);
            		  
            		  
            		  if(detailsData.elementAt(i)[14].equals("PS38")) {
                		  for(int j = 0; j < senddatas.size(); j++){
                			  
                			  
                			  String bettype = detailsData.elementAt(i)[5];
                  			  
                  			  String pankoustr = "";
                  			  String ps38pankoustr = "";
                  			  
                  			  if(bettype.contains("全场让球")) {
                  				  
                  				pankoustr = senddatas.elementAt(j).isnevent.wholeRQPPankou;
                  				ps38pankoustr = senddatas.elementAt(j).event.wholerqppankou;
                  				  
                  			  }else if(bettype.contains("全场大小")) {
                  				pankoustr = senddatas.elementAt(j).isnevent.wholeDXPPankou;
                  				ps38pankoustr = senddatas.elementAt(j).event.wholeDXPPankou;
                  			  }
                  			  
                  			  
                  			  
                  			  
                  			  
                  			  if(!Common.isNum(pankoustr) || !Common.isNum(ps38pankoustr)) {
//                  				System.out.println(df.format(System.currentTimeMillis()) + "  processAutoBet  pankoustr is not a number:" + Arrays.toString(detailsData.elementAt(i)));
//                  				
//                  				Common.logOut("pankoustr:" + pankoustr);
                  				
                  				continue;
                  			  }
                			  
                			  
                			  Long timepassed = System.currentTimeMillis() - Long.parseLong(detailsData.elementAt(i)[12]);
                			  
                			  if(Double.parseDouble(detailsData.elementAt(i)[9]) >= NegativeRatioClient.mainWnd.getbetodd() &&                 					  
                					  Math.abs(pankou - Double.parseDouble(pankoustr))  < 0.001&&
                					  Math.abs(pankou - Double.parseDouble(ps38pankoustr)) < 0.001 &&
                					  detailsData.elementAt(i)[13].equals("0") && 
                					  
                					  timepassed < NegativeRatioClient.mainWnd.getReceiveDataInterval()*1000) {
                				
                				System.out.println(df.format(System.currentTimeMillis()) + "  processAutoBet start to bet:  " + Arrays.toString(detailsData.elementAt(i)));
                				
                				

                    				NegativeRatioClient.isInbet = true;

                    				//autobetCtrMng.dobetgame(detailsData.elementAt(i)[5], detailsData.elementAt(i)[11], senddatas.elementAt(j));

                    				detailsData.elementAt(i)[13] = "1";
                				
                				

                				
                			  }
                			  
                			  
                		  }
            		  }else if(detailsData.elementAt(i)[14].equals("ISN")) {
                		  for(int j = 0; j < isnhgsenddatas.size(); j++){
                			  
                			  
                			  String bettype = detailsData.elementAt(i)[5];
                  			  
                  			  String pankoustr = "";
                  			  String ps38pankoustr = "";
                  			  
                  			  if(bettype.contains("全场让球")) {
                  				  
                  				pankoustr = isnhgsenddatas.elementAt(j).hgevent.wholeRQPPankou;
                  				ps38pankoustr = isnhgsenddatas.elementAt(j).isnevent.wholeRQPPankou;
                  				  
                  			  }else if(bettype.contains("全场大小")) {
                  				pankoustr = isnhgsenddatas.elementAt(j).hgevent.wholeDXPPankou;
                  				ps38pankoustr = isnhgsenddatas.elementAt(j).isnevent.wholeDXPPankou;
                  			  }
                  			  
                  			  
                  			  
                  			  
                  			  
                  			  if(!Common.isNum(pankoustr) || !Common.isNum(ps38pankoustr)) {
//                  				System.out.println(df.format(System.currentTimeMillis()) + "  processAutoBet  pankoustr is not a number:" + Arrays.toString(detailsData.elementAt(i)));
//                  				
//                  				Common.logOut("pankoustr:" + pankoustr);
                  				
                  				continue;
                  			  }
                			  
                			  
                			  Long timepassed = System.currentTimeMillis() - Long.parseLong(detailsData.elementAt(i)[12]);
                			  
                			  if(Double.parseDouble(detailsData.elementAt(i)[9]) >= NegativeRatioClient.mainWnd.getbetodd() && 
                					  eventid.equals(isnhgsenddatas.elementAt(j).hgevent.eventId) && 
                					  Math.abs(pankou - Double.parseDouble(pankoustr))  < 0.001&&
                					  Math.abs(pankou - Double.parseDouble(ps38pankoustr)) < 0.001 &&
                					  detailsData.elementAt(i)[13].equals("0") &&                 					 
                					  timepassed < NegativeRatioClient.mainWnd.getReceiveDataInterval()*1000) {
                				
                				  	System.out.println(df.format(System.currentTimeMillis()) + "  processAutoBet start to bet:  " + Arrays.toString(detailsData.elementAt(i)));
                    				NegativeRatioClient.isInbet = true;

                    				autobetCtrMng.doisnbetgameisn(detailsData.elementAt(i)[5], detailsData.elementAt(i)[11], isnhgsenddatas.elementAt(j));
                    				detailsData.elementAt(i)[13] = "1";

                			  }
                			  
                			  
                		  }
            		  }

            	  }
				
			}
			
			
			
			NegativeRatioClient.isInbet = false;
			
			
		}
		
	}
	
	
    public void setOneRowBackgroundColor() {

        try {  
        	
            DefaultTableCellRenderer tcr = new DefaultTableCellRenderer() {
            	
            	
  
                public Component getTableCellRendererComponent(JTable table,  
                        Object value, boolean isSelected, boolean hasFocus,  
                        int row, int column) {  

                	
                    if (row%2==1) {  
                    	setBackground(new Color(246,246,246));  
                        
                    }else{  
                        setBackground(new Color(222,222,243));  
                    	//setBackground(new Color(1,1,1));  
                      
                    }  
                    
                    setHorizontalAlignment(JLabel.CENTER);
  
                    return super.getTableCellRendererComponent(table, value,  
                            isSelected, hasFocus, row, column);  
                }  
            };  
            int columnCount = table.getColumnCount();  
            for (int i = 0; i < columnCount; i++) {  
            	table.getColumn(table.getColumnName(i)).setCellRenderer(tcr);
            }  
        } catch (Exception ex) {  
            ex.printStackTrace();  
        }  
    
    }  
	
	
	
	

    public class MyTableModel extends AbstractTableModel  
    {  
        /**
		 * 
		 */
		private static final long serialVersionUID = 1L;
		/* 
         * 这里和刚才一样，定义列名和每个数据的值 
         */  
        String[] columnNames =  
        { "序号", "时间",  "联赛", "比赛时间", "球队", "类型", "盘口", "皇冠", "副水", "合并赔率","副网"};
        
       // { "序号", "联赛", "时间", "球队", "类型", "盘口", "皇冠", "PS38", "合并赔率","1","2","时间"};
        

  
        /** 
         * 构造方法，初始化二维数组data对应的数据 
         */  
        public MyTableModel()  
        {  

        }  
  
        // 以下为继承自AbstractTableModle的方法，可以自定义  
        /** 
         * 得到列名 
         */  
        @Override  
        public String getColumnName(int column)  
        {  
            return columnNames[column];  
        }  
          
        /** 
         * 重写方法，得到表格列数 
         */  
        @Override  
        public int getColumnCount()  
        {  
            return columnNames.length;  
        }  
  
        /** 
         * 得到表格行数 
         */  
        @Override  
        public int getRowCount()  
        {         
	        if(null == detailsData){
	    		return 0;
	    	}
            return detailsData.size();  
        }  
  
        /** 
         * 得到数据所对应对象 
         */  
        @Override  
        public Object getValueAt(int rowIndex, int columnIndex)  
        {  
            //return data[rowIndex][columnIndex];
        	
        	if(detailsData.size() == 0) {
        		return null;
        	}
        	
        	if(columnIndex==10) {
        		return detailsData.elementAt(rowIndex)[14];
        	}
        	
        	return detailsData.elementAt(rowIndex)[columnIndex];
        }  
  
        /** 
         * 得到指定列的数据类型 
         */  
        @Override  
        public Class<?> getColumnClass(int columnIndex)  
        {  
        	
        	return String.class;
        	
//        	if(detailsData.size() == 0){
//        		return String.class;
//        	}
//
//            return detailsData.elementAt(0)[columnIndex].getClass();
        	
        }  
  
        /** 
         * 指定设置数据单元是否可编辑.这里设置"姓名","学号"不可编辑 
         */  
        @Override  
        public boolean isCellEditable(int rowIndex, int columnIndex)  
        {  
            return false;
        }  
          
        /** 
         * 如果数据单元为可编辑，则将编辑后的值替换原来的值 
         */  
        @Override  
        public void setValueAt(Object aValue, int rowIndex, int columnIndex)  
        {  
            detailsData.elementAt(rowIndex)[columnIndex] = (String)aValue;  
            /*通知监听器数据单元数据已经改变*/  
            fireTableCellUpdated(rowIndex, columnIndex);  
        }  
        
        public void updateTable(){
        	fireTableDataChanged();
        }
        
  
    }  
	
	
	
	private boolean isInRange(double hgodd, double ps38odd) {
		
		double sideMinodd = NegativeRatioClient.mainWnd.getsideMinodd();
		double sumMinodd = NegativeRatioClient.mainWnd.getCtypesumMinodd();
		
		double sideMaxodd = NegativeRatioClient.mainWnd.getsideMaxodd();
		double sumMaxodd = NegativeRatioClient.mainWnd.getsumMaxodd();
		
		
		DecimalFormat df = new DecimalFormat("#.000");
		
		if(ps38odd < 0.0) {
			ps38odd = Double.parseDouble(df.format(2.0 + ps38odd));
		}
		

		
		if(hgodd >= sideMinodd && ps38odd >= sideMinodd && (hgodd + ps38odd) >= sumMinodd && hgodd <= sideMaxodd && ps38odd <= sideMaxodd && (hgodd+ps38odd) <= sumMaxodd) {
			return true;
		}
		
		return false;
	}



	public void showBetWnd() {
		
		if(detailsData != null &&detailsData.size()  != 0) {
			
			if(betwnd.isVisible() || NegativeRatioClient.mainWnd.getautobet() == true) {
				return;
			}
			
			if(betwnd.setgame(detailsData.elementAt(0)[5], detailsData.elementAt(0)[11], localgamedetails.elementAt(0))) {
				betwnd.setVisible(true);
			}  
			
		}
		

		
	}
	
	
	
	public boolean isIntime(String type, ISNEvent hgevent) {
		
		try {
			

			int danshiMaxTime = NegativeRatioClient.mainWnd.getDanshiMaxTime();
			int danshiMinTime = NegativeRatioClient.mainWnd.getDanshiMinTime();
			
			SimpleDateFormat dfmin = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			
			
			if(type.contains("全场")) {
				if(hgevent.duringTime.equals("")) {//单式
					Long eventtime = dfmin.parse(hgevent.eventTime).getTime();
					
					if(eventtime - System.currentTimeMillis() > danshiMaxTime*60*1000 || eventtime - System.currentTimeMillis() < danshiMinTime*60*1000) {
						return false;
					}
					
				}
			}
			
			
		
		}catch(Exception e) {
			e.printStackTrace();
		}
		
		
		return true;
		
	}
	
	
	
	
}
